package com.sp.system.user.core.security;

import com.google.gson.Gson;
import com.sp.system.user.core.entity.SecurityUserDetails;
import com.sp.system.user.core.entity.User;
import com.sp.system.user.core.utils.BasePropertiesUtil;
import com.sp.system.user.core.utils.ResponseUtil;
import com.sp.system.user.core.utils.enums.PermissionEnum;
import com.sp.system.user.core.utils.security.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Describle  用户登录校验
 * @author chenanhai
 * @date 2019年9月19日
 */
@Slf4j
public class LoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {


    private ThreadLocal<Integer> rememberMe = new ThreadLocal<>();
    private AuthenticationManager authenticationManager;
    public LoginAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        super.setFilterProcessesUrl(BasePropertiesUtil.projectName + "/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 从输入流中获取到登录的信息
        try {
            BufferedReader reader = request.getReader();
            Gson gson = new Gson();
            User loginUser = gson.fromJson(reader, User.class);
//            rememberMe.set(loginUser.getRememberMe());
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginUser.getLoginName(), loginUser.getPassword(), new ArrayList<>())
            );
        } catch (IOException e) {
            log.error("登录异常：：{}",e);
            ResponseUtil.out(response,ResponseUtil.resultMap(PermissionEnum.USER_ERROR.getStatus(), PermissionEnum.USER_ERROR.getMessage()));
        } catch (Exception e){
            log.error("登录异常：：{}",e);
            ResponseUtil.out(response,ResponseUtil.resultMap(PermissionEnum.USER_ERROR.getStatus(), PermissionEnum.USER_ERROR.getMessage()));
        }
        return super.attemptAuthentication(request, response);
    }

    /**
     *  登录成功
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //生成token
        log.debug("登录成功{UsernamePasswordAuthenticationFilter}");
        final User user = (User) authResult.getPrincipal();
        final SecurityUserDetails securityUserDetails = new SecurityUserDetails(user);
        final String token = JwtTokenUtil.tokenPrefix + JwtTokenUtil.generateAccessToken(securityUserDetails);
        response.setHeader(JwtTokenUtil.tokenHeader, token);
        ResponseUtil.out(response,ResponseUtil.resultMap(PermissionEnum.LOGIN_SUCCESS.getStatus(), PermissionEnum.LOGIN_SUCCESS.getMessage()));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        log.error("登录失败{UsernamePasswordAuthenticationFilter}");
        ResponseUtil.out(response,ResponseUtil.resultMap(PermissionEnum.USER_ERROR.getStatus(), PermissionEnum.USER_ERROR.getMessage()));
    }
}
